package com.xxg.renrensearch.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xxg.renrensearch.baidu.BosManager;
import com.xxg.renrensearch.baidu.ImageRetrieval;
import com.xxg.renrensearch.dao.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 百度接口实现
 *
 * @author xuxiaogang
 * @date 2021-12-15
 */
@Service
public class BaiduService {
    private final Logger logger = LoggerFactory.getLogger(BaiduService.class);
    private final BosManager bosManager;
    private final ImageRetrieval imageRetrieval;

    public BaiduService(BosManager bosManager, ImageRetrieval imageRetrieval) {
        this.bosManager = bosManager;
        this.imageRetrieval = imageRetrieval;
    }

    private Map<String, Map<String, String>> uploadImageTask(List<Product> productList) {
        logger.info("将更新或新增的商品中新的图片上传，商品数量:" + productList.size());
        // 更新图片并保存上传成功的图片信息为创建图片索引做准备
        Map<String, Map<String, String>> newImages = new HashMap<>(productList.size() * 4 / 3 + 1);
        for (Product product : productList) {
            List<String> images = JSON.parseObject(product.getSpuThumbAll(), new TypeReference<List<String>>() {
            });
            String spuId = String.valueOf(product.getSpuId());
            String shopId = String.valueOf(product.getShopId());
            String skuId = String.valueOf(product.getSkuId());
            for (String image : images) {
                boolean f;
                try {
                    f = bosManager.uploadIfNotExist(image, spuId, shopId, skuId);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    continue;
                }
                if (f) {
                    Map<String, String> brief = new HashMap<>(5);
                    brief.put("spuid", spuId);
                    brief.put("shopid", shopId);
                    brief.put("skuId", skuId);
                    newImages.put(image, brief);
                }
            }
        }
        return newImages;
    }

    /**
     * 新增或更新图片和图片索引 如果图片变更则新增
     *
     * @param productList 待更新的商品列表
     */
    @Async("uploadImagesExecutor")
    public void addOrUpdatePicture(List<Product> productList) {
        Map<String, Map<String, String>> newImages = uploadImageTask(productList);
        logger.info("商品中新的图片上传完毕,新增图片数量:" + newImages.size());
        if (newImages.size() > 0) {
            imageRetrieval.batchCreateImageIndex(newImages);
        }
    }
}
